package com.cby.ssm.controller;

import com.cby.ssm.entity.UserEntity;
import com.cby.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by 13296 on 2017/7/12.
 */
@Controller
public class LoginHandler {
    @Autowired
    UserService fun;

    /**
     * 登录
     * @param account
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login.do")
    public String login(String account, Model model, String password, HttpServletRequest request){
        HttpSession session = request.getSession();
        try {
            UserEntity u = fun.login(account,password);
            session.setAttribute("currentUser",u);
        }catch (Exception e){
            model.addAttribute("message",e.getMessage());
            return "forward:/login.jsp";
        }
        return "redirect:/index.do";
    }
    @RequestMapping("/index.do")
    public String index(){
        return "index";
    }
    @RequestMapping("/welcome.do")
    public String welcome(){
        return "welcome";
    }

    /**
     *退出登录
     * @return
     */
    @RequestMapping("/logout.do")
    public String logout(HttpSession session){
        //让session失效
        session.invalidate();
        return "redirect:/login.jsp";
    }

    /**
     * 添加
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,path="/addUser.do")
    public String enrollView(){
        return null;
    }

    @RequestMapping(method=RequestMethod.POST,path="/addUser.do")
    public String addUser(String account,String passwordAgain, String password, String name, String sex,
                          String telephone, String email, String address,Model model,HttpServletRequest request)throws Exception{
        //HttpSession session=request.getSession();
        try{
            fun.addUser(account,passwordAgain,password,name,sex,telephone,email,address);
        }catch(Exception e){
            model.addAttribute("message", e.getMessage());
            return "addUser";
        }
        return "redirect:/deleteUser.do?pn=1";
    }

}
